class ManaController < ApplicationController
  before_filter :correct_bili_name?, :limit_bili_users
  layout "need_bili_name"

  require 'digest/md5'

  #默认查看正常的新推荐
  def index
    @pickups = Pickup.all :conditions => "status = 0 and (ptype = 0 or ptype = 5)", :order => "id"
    render :action => :list
  end

  def list
    @pickups = Pickup.all :conditions => ["status = 0 and ptype = ?", params[:id]], :order => "id"
  end

  def list_allow
    @pickups = Pickup.all :conditions => "status = 1", :order => "id desc"
  end
  
  def list_use
    @pickups = Pickup.all :include => :pickup_password, :conditions => "status = 2", :order => "id desc"
	render :action => :list_allow
  end

  def list_ignore
    @pickups = Pickup.all :conditions => "status = 3", :order => "id desc"
  end

  def show
    @pickup = Pickup.find params[:id], :include => :pickup_password
    @num = WeeklyResult.count :include => :weekly_result_work, :conditions => ["wid = ?", @pickup.avid]
    @min_rank = WeeklyResult.first :select => "score_rank, weekly_id", :include => :weekly_result_work,
                                     :conditions => ["weekly_result_works.wid = ?", @pickup.avid],
                                     :order => "score_rank"
  end

  def allow
    pickup = Pickup.find params[:id]
    pickup.update_attribute :status, 1
    PickupLog.create :pickup_id => pickup.id, :otype => 0, :uname => current_bili_user
    flash[:notice] = "#{pickup.uname}的推荐『#{pickup.wname}』已通过审核"
    redirect_to :action => :index
  end

  def use
    pickup = Pickup.find params[:id]
    pickup.update_attribute :status, 2
    PickupLog.create :pickup_id => pickup.id, :otype => 1, :uname => current_bili_user
    unless pickup.pickup_password
      begin
        PickupPassword.create! :pickup_id => pickup.id, :password => Digest::MD5.hexdigest("nitori#{pickup.uname}#{pickup.avid}")[0..8]
      rescue
        PickupPassword.create! :pickup_id => pickup.id, :password => Digest::MD5.hexdigest("nitori#{pickup.uname}#{pickup.avid}")[1..9]
      end
    end
    pickup = Pickup.find params[:id]
    flash[:notice] = "av#{pickup.avid}启用，密码为『#{pickup.pickup_password.password}』"
    redirect_to :action => :list_use
  end

  def ignore
    pickup = Pickup.find params[:id]
    pickup.update_attribute :status, 3
    PickupLog.create :pickup_id => pickup.id, :otype => 2, :uname => current_bili_user
    flash[:notice] = "#{pickup.uname}的推荐『#{pickup.wname}』已忽略"
    redirect_to :action => :index
  end

  #代提交
  def new
    @pickup = Pickup.new
  end

  def create
    @pickup = Pickup.new params[:pickup]
    work = @pickup.work
    @pickup.ptype = 5
    @pickup.wname = (work.name rescue "[未知投稿名称]")
    if @pickup.save
      PickupLog.create :pickup_id => @pickup.id, :uname => current_bili_user, :otype => 3
      flash[:notice] = "推荐『#{@pickup.wname}』提交成功"
      redirect_to :action => :index
    else
      render :action => :new
    end
  end
end
